<template>
  <div class="user-list">
    <h2>用户列表</h2>

    <!-- 查询输入框 -->
    <div class="search-container">
      <input 
        v-model="queryId" 
        @input="searchUsersById" 
        placeholder="请输入用户ID进行搜索"
        class="search-input" 
      />
    </div>

    <div v-if="loading" class="loading">
      <p>Loading users...</p>
    </div>

    <div v-else-if="error" class="error-message">
      <p>{{ error }}</p>
      <button @click="fetchUsers" class="retry-button">Retry</button>
    </div>
    
    <div v-else-if="users.length === 0" class="no-users">
      <p>No users found. Try adding a new user.</p>
    </div>
    
    <table v-else class="user-table">
      <thead>
        <tr>
          <th>编码ID</th>
          <th>用户名</th>
          <th>邮箱地址</th>
          <th>电话</th>
          <th>性别</th>
          <th>生日</th>
          <th>备注</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.userName }}</td>
          <td>{{ user.email }}</td>
          <td>{{ user.phone }}</td>
          <td>
            <!-- 修改后的性别显示逻辑 -->
            <span v-if="user.gender === 'male'">男</span>
            <span v-else-if="user.gender === 'female'">女</span>
            <span v-else>{{ user.gender }}</span> <!-- 如果 gender 不是 male 或 female，直接显示原始值 -->
          </td>
          <td>{{ formatBirthday(user.birthday) }}</td>
          <td>{{ user.note }}</td>
          <td class="action-buttons">
            <router-link :to="`/edit/${user.id}`" class="edit-btn">编辑</router-link>
            <button 
              @click="deleteUser(user.id)" 
              class="delete-btn"
              :disabled="deleting"
            >
              {{ deleting ? 'Deleting...' : '删除' }}
            </button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { UserService } from '@/services/userService';
import { useRouter } from 'vue-router';

const users = ref([]);
const loading = ref(true);
const error = ref(null);
const deleting = ref(false);
const queryId = ref(''); // 查询条件字段（用户ID）
const router = useRouter();

// 格式化生日字段
const formatBirthday = (birthday) => {
  if (!birthday) return '';
  const date = new Date(birthday);
  return date.toLocaleDateString();
};

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  error.value = null;
  try {
    users.value = await UserService.getAllUsers();
    loading.value = false;
  } catch (err) {
    error.value = err.response?.data?.message || 'Failed to fetch users. Please check your connection.';
    loading.value = false;
  }
};

// 根据用户ID查询用户
const searchUsersById = async () => {
  loading.value = true;
  error.value = null;
  try {
    if (!queryId.value.trim()) {
      // 如果没有输入查询条件，获取所有用户
      await fetchUsers();
    } else {
      // 根据ID查询用户
      const id = parseInt(queryId.value.trim(), 10);
      if (isNaN(id)) {
        error.value = '请输入有效的用户ID';
        users.value = [];
      } else {
        const user = await UserService.getUserById(id);
        users.value = user ? [user] : []; // 将用户放入数组中以便统一渲染
      }
    }
    loading.value = false;
  } catch (err) {
    error.value = err.response?.data?.message || 'Failed to fetch user. Please check your connection.';
    loading.value = false;
  }
};

// 删除用户
const deleteUser = async (id) => {
  if (confirm('是否确认删除当前用户?')) {
    deleting.value = true;
    try {
      await UserService.deleteUser(id);
      users.value = users.value.filter(user => user.id !== id);
    } catch (err) {
      error.value = err.response?.data?.message || 'Failed to delete user';
    } finally {
      deleting.value = false;
    }
  }
};

onMounted(fetchUsers);

// 监听路由变化，更新用户列表
watch(
  () => router.currentRoute.value.state,
  (newState) => {
    if (newState && newState.updatedUser) {
      const updatedUser = newState.updatedUser;
      const index = users.value.findIndex(user => user.id === updatedUser.id);
      if (index !== -1) {
        users.value[index] = updatedUser;
      }
    }
  },
  { deep: true }
);
</script>

<style scoped>
.user-list {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.loading, .error-message, .no-users {
  text-align: center;
  padding: 20px;
}

.error-message {
  color: red;
}

.search-container {
  margin-bottom: 20px;
}

.search-input {
  padding: 10px;
  margin: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 200px;
}

.user-table {
  width: 900px;
  border-collapse: collapse;
}

.user-table th, .user-table td {
  border: 1px solid #ddd;
  padding: 20px;
  text-align: center;
}

.user-table th:nth-child(3), .user-table td:nth-child(3),
.user-table th:nth-child(6), .user-table td:nth-child(6),
.user-table th:nth-child(7), .user-table td:nth-child(7) {
  width: 200px;
}

.user-table th:nth-child(4), .user-table td:nth-child(4) { 
  width: 150px;
}

.user-table th:nth-child(5), .user-table td:nth-child(5) { 
  width: 150px;
}

.user-table th:nth-child(8), .user-table td:nth-child(8) { 
  width: 150px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.edit-btn, .delete-btn {
  padding: 5px 10px;
  text-decoration: none;
}

.edit-btn {
  color: blue;
}

.delete-btn {
  color: red;
}
</style>